package com.spring.controller;

import com.spring.ServiceImpl.UserService;
import com.spring.mapper.UserMapper;
import com.spring.pojo.User;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;



    @RequestMapping("add")
    //@ResponseBody
    public void add(User user, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        userService.add(user);
        request.getRequestDispatcher("/user/listUser").forward(request,response);
    }

    @RequestMapping("listUser")
    public String listUser(Model model){
        List<User> list=userService.listUser();
        model.addAttribute("list",list);
        return "list";
    }

    @RequestMapping("login")
    public String login(Model model, User user, HttpSession session){
       User user1= userService.login(user);
       if (user1!=null){
           session.setAttribute("user",user1);
           return "redirect:/user/listUser";
       }
       return "add";
    }

    @RequestMapping("/")
    public String showRegister(){
        return "login";
    }

    @RequestMapping("del")
    public void del(int id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        userService.del(id);
        request.getRequestDispatcher("/user/listUser").forward(request,response);
    }


}
